﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ControlModule.Models;
using ControlModule.Security;

namespace ControlModule.Controllers
{
    public class PersonalController : Controller
    {
        private CmDbEntities db = new CmDbEntities();
        //
        // GET: /Cabinet/

        [Authorize(Roles = "STUDENT")]
        public ActionResult CabinetPage()
        {
            List<LabworkViewModel> labworkViewModels = new List<LabworkViewModel>();

            int userId = MyMembershipProvider.GetCurrentUserInstance().Id;

            List<PublishedLabwork> publishedLabworks = (
                from la in db.Labwork
                from gr in db.Group
                from us in db.User
                from pl in db.PublishedLabwork
                where pl.LabworkId == la.Id
                where pl.GroupId == gr.Id
                where us.GroupId == gr.Id
                where us.Id == userId
                select pl).ToList();

            foreach (PublishedLabwork publishedLabwork in publishedLabworks)
            {
                LabworkViewModel labworkViewModel = new LabworkViewModel();
                labworkViewModel.Id = publishedLabwork.LabworkId;

                Labwork labwork = db.Labwork.FirstOrDefault(l => l.Id == publishedLabwork.LabworkId);
                if (labwork != null)
                {
                    labworkViewModel.Title = labwork.Title;
                    labworkViewModel.Topic = labwork.Topic;
                    labworkViewModel.Descr = labwork.Descr;
                }

                User user = db.User.FirstOrDefault(us => us.Id == publishedLabwork.TutorId);
                if (user != null)
                    labworkViewModel.Tutor = user.FirstName + " " + user.LastName;

                if (publishedLabwork.PublicDate != null) 
                    labworkViewModel.PublicDate = (DateTime) publishedLabwork.PublicDate;
                if (publishedLabwork.FinishDate != null) 
                    labworkViewModel.FinishDate = (DateTime) publishedLabwork.FinishDate;

                labworkViewModels.Add(labworkViewModel);
            }

            return View(labworkViewModels);
        }

        [Authorize(Roles = "STUDENT")]
        public ActionResult EditDataPage()
        {
            return View();
        }
    }
}
